export type Channel = {
  id: number
  name: string
}

export type MoreAction = {
  visible: boolean
  channelId: string
}

export type Article = {
  art_id: string
  title: string
  aut_id: string
  comm_count: number
  pubdate: string
  aut_name: string
  is_top: number
  cover: {
    type: string
    images: string[]
  }
}

export type Articles = {
  [index: number]: {
    timestamp: string
    list: Article[]
  }
}

export type HomeType = {
  userChannels: Channel[]
  allChannels: Channel[]
  articles: Articles
  moreAction: MoreAction
}

export type ArticlePayload = {
  channelId: number
  timestamp: string
  list: Article[]
  loadMore: boolean
}

export type HomeAction =
  | {
      type: 'home/userChannels'
      payload: Channel[]
    }
  | {
      type: 'home/allChannels'
      payload: Channel[]
    }
  | {
      type: 'home/setChannelsList'
      payload: ArticlePayload
    }
  | {
      type: 'home/moreAction'
      payload: MoreAction
    }

const initValue: HomeType = {
  userChannels: [],
  allChannels: [],
  articles: {},
  moreAction: {
    visible: false,
    channelId: '',
  },
}
export default function reducer(state = initValue, action: HomeAction) {
  // const { type, payload } = action
  // const { list, channelId, timestamp, loadMore } = payload
  switch (action.type) {
    case 'home/userChannels':
      return {
        ...state,
        userChannels: action.payload,
      }
    case 'home/allChannels':
      return {
        ...state,
        allChannels: action.payload,
      }
    case 'home/setChannelsList':
      return {
        ...state,
        articles: {
          ...state.articles,
          [action.payload.channelId]: {
            timestamp: action.payload.timestamp,
            list: action.payload.loadMore ? [...state.articles[action.payload.channelId].list, ...action.payload.list] : action.payload.list,
          },
        },
      }
    case 'home/moreAction':
      return {
        ...state,
        moreAction: action.payload,
      }
    default:
      return state
  }
}
